package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.print.attribute.standard.MediaSize;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
//    @Scheduled(cron = "0 * * * *  ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单 {}",LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //查询所有状态为待付款以及时间小于当前时间-15分钟的订单
        List<Orders> orders=orderMapper.getByStatusAndTime(Orders.PENDING_PAYMENT,localDateTime);
        if(orders==null|| orders.isEmpty()){
            return;
        }
        //修改订单状态为取消，以及取消时间和取消原因
        for (Orders order : orders) {
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("支付超时");
            orderMapper.update(order);
        }
    }


//    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单 {}",LocalDateTime.now());
        LocalDateTime localDateTime=LocalDateTime.now().plusMinutes(-60);

        List<Orders> orders = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if(orders==null|| orders.isEmpty()){
            return;
        }
        for (Orders order : orders) {
            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);
        }
    }
}
